package com.lxk.service.impl;

import com.lxk.redis.RedisKey;
import com.lxk.redis.RedisUtil;
import com.lxk.service.LoginService;
import com.lxk.util.exception.GlobalException;
import com.lxk.vo.result.CodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author JohnSoybean
 * @create 2020/7/13 18:42
 * @description
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisUtil redisUtil;

    private static final Long mockId = 1L;
    private static final String mockToken = "1A2B3C4D5E6F7G8H9I0J";

    /**
     * 生成token
     * @return
     */
    private String generateToken(){
        UUID uuid = UUID.randomUUID();
        String token = uuid.toString();
        return token;
    }

    public String mockSetAuth() {
        String key = redisUtil.joinKey(RedisKey.TOKEN.getPrefix(), mockToken);
        boolean flag = redisUtil.set(key, mockId, RedisKey.TOKEN.getExpire());
        if (!flag) {
            throw new GlobalException(CodeMsg.REDIS_CONNECT_ERR);
        }
        System.out.println("##测试账号登录##");
        return mockToken;
    }

    public String setAuth(Long id) {
        String token = generateToken();
        String key = redisUtil.joinKey(RedisKey.TOKEN.getPrefix(), token);
        redisUtil.set(key, id, RedisKey.TOKEN.getExpire());
        System.out.println("##登录##");
        System.out.println(""+key);
        System.out.println("ID:"+id);
        return token;
    }

    public Long authToken(String token) {
        String key = redisUtil.joinKey(RedisKey.TOKEN.getPrefix(), token);
        Integer value = (Integer)redisUtil.get(key);
        //判断权限
        if (value == null) {
            //token不存在或已过期
            return null;
        }else {
            //token存在且未过期
            Long id = value.longValue();
            redisUtil.expire(key, RedisKey.TOKEN.getExpire());
            return id;
        }
    }

    public void removeToken(String token) {
        String key = redisUtil.joinKey(RedisKey.TOKEN.getPrefix(), token);
        redisUtil.del(key);
    }
}
